﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VFCons
{
	public partial class RadioButtonGroupTab : UserControl
	{
		public event EventHandler CheckedChanged;
		public RadioButtonGroupTab()
		{
			InitializeComponent();
			rbuttons.Add(radioButton1);
		}
		private List<RadioButton> rbuttons = new List<RadioButton>();
		private string[] _names = new string[1] { "radioButton1" };

		public string[] Names
		{
			get { return _names; }
			set
			{
				if (value == null || value.Length == 0)
				{
					_names = new string[1] { "radioButton1" };
				}
				else
					_names = value;
				InitRButons(_names);
				Invalidate();
			}
		}

		private RadioButton createRButton(string name)
		{
			var rb = new RadioButton();
			rb.AutoSize = true;
			rb.Location = new System.Drawing.Point(3, 3);
			rb.Name = "rb_" + name;
			rb.Size = new System.Drawing.Size(124, 19);
			rb.TabIndex = 0;
			rb.TabStop = true;
			rb.Text = name;
			rb.UseVisualStyleBackColor = true;
			rb.Anchor = AnchorStyles.None;
			return rb;
		}

		private void InitRButons(string[] names)
		{
			tableLayoutPanel1.Controls.Clear();
			tableLayoutPanel1.ColumnStyles.Clear();

			tableLayoutPanel1.ColumnCount = names.Length;
			float w = 100.0F / names.Length;
			for (int i = 0; i < names.Length; i++)
			{
				tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, w));
			}
			
			//tableLayoutPanel1.RowCount = 1;
			//tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));

			rbuttons.Clear();

			foreach (var n in names)
			{
				var rb = createRButton(n);
				rb.CheckedChanged += Rb_CheckedChanged;
				tableLayoutPanel1.Controls.Add(rb);
			}
		}

		private void Rb_CheckedChanged(object sender, EventArgs e)
		{
			RadioButton rb = sender as RadioButton;
			if (rb.Checked)
			{
				if (CheckedChanged != null) CheckedChanged(sender, e);
			}
			System.Diagnostics.Debug.WriteLine("RB {0}={1}", rb.Text, rb.Checked);
		}

		public int SelectIndex
		{
			get
			{
				for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
				{
					RadioButton rb = (RadioButton)tableLayoutPanel1.Controls[i];
					if (rb.Checked) return i;
				}
				return -1;
			}
			set
			{
				for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
				{
					RadioButton rb = (RadioButton)tableLayoutPanel1.Controls[i];
					if (i == value) rb.Checked = true;
					else rb.Checked = false;
				}
			}
		}
	}
}
